package chat.keepWind.event;

import chat.keepWind.handle.KeepWindDecoder;
import chat.keepWind.handle.KeepWindEncoder;
import chat.keepWind.handle.RcvFileInboundHandler;
import chat.keepWind.util.GlobalConst;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

public class ReceiveFile {
	
	public void receive() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup(1);
        Bootstrap bootstrap = new Bootstrap();
      
        try {
            bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(65535))
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast(new KeepWindDecoder()); //解密
                            pipeline.addLast(new KeepWindEncoder(null)); //编码
                            pipeline.addLast(new RcvFileInboundHandler());//处理数据
                        }
                    });
            Channel channel = bootstrap.bind(GlobalConst.FILE_PORT).sync().channel();
            
            //等待关闭
            channel.closeFuture().sync();
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
